package com.lenovo.smarttraffic.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.api.onDateChoose;
import com.lenovo.smarttraffic.bean.DatePickerBean;
import com.lenovo.smarttraffic.bean.GsonBean.CarPenccyBean;
import com.lenovo.smarttraffic.ui.fragment.CalendarDialog;
import com.lenovo.smarttraffic.ui.fragment.PickerDateDialogFragment;
import com.lenovo.smarttraffic.ui.fragment.RangeDateDialog;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * Created by Caleb.F
 * on 2020-03-08
 * at 22:17
 */
public class PenccyQueryActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mImageView;
    private TextView mTvStartDate;
    private TextView mTvEndDate;
    private LineChart mMyLinechat;
    private FragmentManager fm;
    private DatePickerBean mDatePickerBean;
    private ProgressDialog mProgressDialog;
    private List<CarPenccyBean.ROWSDETAILBean> mlist;
    private SimpleDateFormat mSimpleDateFormat;
    private long calendarStartMills;
    private long calendarEndMills;
    private static final String TAG = "PenccyQueryActivity";
    private String[] labels = new String[]{
            "学院路", "联想路", "医院路", "幸福路", "环城快速路", "环城高速"
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mProgressDialog = new ProgressDialog(this);
        mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        mProgressDialog.setMessage("网络请求中。。。");
        getData();
        fm = getSupportFragmentManager();
        initView();
    }

    private void getData() {
        mProgressDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName", "user1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        VolleyUtil.post("GetAllCarPeccancy.do", jsonObject, new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                if (jsonObject.optString("RESULT").equals("S")) {
                    mProgressDialog.dismiss();
                    mlist = new Gson().fromJson(response, CarPenccyBean.class).getROWS_DETAIL();
                    showPrimaryData();
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    /**
     * 展示第一次數據
     */
    private void showPrimaryData() {
        try {
            calendarStartMills = mSimpleDateFormat.parse(mTvStartDate.getText().toString()).getTime();
            calendarEndMills = mSimpleDateFormat.parse(mTvEndDate.getText().toString()).getTime();
            drawChart(handlerData(new DatePickerBean(calendarStartMills, calendarEndMills)));
            mProgressDialog.dismiss();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        initToolBar("违章查询");
        mImageView = findViewById(R.id.imageView);
        mTvStartDate = findViewById(R.id.tv_start_date);
        mTvEndDate = findViewById(R.id.tv_end_date);
        mMyLinechat = findViewById(R.id.my_linechat);
        mImageView.setOnClickListener(this);
        mTvStartDate.setOnClickListener(this);
        mTvEndDate.setOnClickListener(this);
        initChat();
    }

    private void initChat() {
        //x轴
        XAxis xAxis = mMyLinechat.getXAxis();
        xAxis.setDrawGridLines(false);
        //显示的内容设置成false
        xAxis.setCenterAxisLabels(false);

        xAxis.setAxisMinimum(-0.5f);
        xAxis.setAxisMaximum(5.5f);


        xAxis.setTextColor(Color.parseColor("#558E95"));
        xAxis.setAxisLineColor(Color.parseColor("#558E95"));
        xAxis.setGranularity(1);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return labels[(int) value];
            }
        });
//y轴
        YAxis axisLeft = mMyLinechat.getAxisLeft();
        axisLeft.setDrawAxisLine(false);
        axisLeft.setAxisMinimum(0);
        axisLeft.enableAxisLineDashedLine(10f, 50f, 0);
        YAxis axisRight = mMyLinechat.getAxisRight();
        axisRight.setEnabled(false);
        //描述
        Description description = new Description();
        description.setText("次数");
        description.setTextSize(20);
        description.setTextColor(Color.GRAY);
        description.setPosition(150, 50);
        mMyLinechat.setDescription(description);
    }


    @Override
    protected int getLayout() {
        return R.layout.activity_penncy_query;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView:
                fm.beginTransaction().add(new RangeDateDialog(), "RangeDatedialog").commit();
                break;

            case R.id.tv_start_date:
                CalendarDialog calendarDialog = CalendarDialog.newInstance(mTvStartDate.getText().toString());
                fm.beginTransaction().add(calendarDialog, "CalendarDialog").commit();
                calendarDialog.setonDateChoose(new onDateChoose() {
                    @Override
                    public void getDate(Date date) {
                        calendarStartMills = date.getTime();
                        mTvStartDate.setText(getDateString(date));
                        chooseDate();
                    }
                });
                break;
            case R.id.tv_end_date:
                PickerDateDialogFragment pickerDateDialogFragment =
                        PickerDateDialogFragment.newInstance(mTvEndDate.getText().toString());
                pickerDateDialogFragment.setonDateChoose(new onDateChoose() {
                    @Override
                    public void getDate(Date date) {
                        mTvEndDate.setText(getDateString(date));
                        calendarEndMills = date.getTime();
                        chooseDate();
                    }
                });
                fm.beginTransaction().add(pickerDateDialogFragment, "datapickerDialog").commit();
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = false)
    public void getEventData(DatePickerBean datePickerBean) {
        mDatePickerBean = datePickerBean;
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mDatePickerBean != null && mlist != null) {
                        mTvStartDate.setText(mDatePickerBean.getStartDate());
                        mTvEndDate.setText(mDatePickerBean.getEndDate());
                        drawChart(handlerData(mDatePickerBean));
                    }
                    break;
            }
            return false;
        }
    });

    private void drawChart(HashMap<String, Integer> dataMap) {
        ArrayList<Entry> entries = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            entries.add(new Entry(i, dataMap.get(labels[i])));
        }
        LineDataSet lineDataSet = new LineDataSet(entries, "");
        lineDataSet.setColor(Color.RED);
        lineDataSet.setCircleColor(Color.RED);
        lineDataSet.setDrawCircles(true);
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setDrawValues(true);
        LineData lineData = new LineData(lineDataSet);
        mMyLinechat.setData(lineData);
        mMyLinechat.invalidate();
    }


    /**
     * 筛选数据
     * @param datePickerBean
     * @return
     *
     */
    private HashMap<String, Integer> handlerData(DatePickerBean datePickerBean) {
        HashMap<String, Integer> resultMap = new HashMap<>();
        for (CarPenccyBean.ROWSDETAILBean item : mlist) {
            String date = item.getPdatetime().split(" ")[0];
            try {
                long time = mSimpleDateFormat.parse(date).getTime();
                if (time >= datePickerBean.getStartTime() && time <= datePickerBean.getEndTime()) {
                    //hashMap去存统计数据

                    if (resultMap.containsKey(item.getPaddr())) {
                        resultMap.put(item.getPaddr(), resultMap.get(item.getPaddr()) + 1);
                    } else {
                        resultMap.put(item.getPaddr(), 1);
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //相关路段没有数据的需要设置为0,否则会报错
        for (String label : labels) {
            if(!resultMap.containsKey(label)){
                resultMap.put(label,0);
            }
        }
        return resultMap;
    }

    public String getDateString(Date date) {
        return mSimpleDateFormat.format(date);
    }

    private void chooseDate() {
        if (calendarEndMills < calendarStartMills) {
            calendarEndMills = calendarStartMills;
            mTvEndDate.setText(mTvStartDate.getText().toString());
        }
        drawChart(handlerData(new DatePickerBean(calendarStartMills,calendarEndMills)));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
